<template>
  <div>
    <el-tabs
      ref="tabs"
      v-show="tabs.length"
      :value="activeTabKey"
      type="border-card"
      closable
      @tab-click="onTabClick"
      @tab-remove="onTabRemove"
    >
      <el-tab-pane
        v-for="tab in tabs"
        :key="tab.key"
        :name="tab.key"
        :label="tab.title"
        :style="{
          height: paneHeight + 'px',
          overflow: 'auto'
        }"
        element-loading-background="rgba(0, 0, 0, 0)"
        v-loading="tab.loading"
      >
        <component :is="tab.content" />
      </el-tab-pane>
    </el-tabs>

    <el-dropdown
      ref="tabsDropdown"
      placement="bottom"
      trigger="manual"
      :hide-timeout="5000"
      style="position: absolute;left:0px;top:0px;"
      @command="onContextmenuCommand">
      <span></span>
      <el-dropdown-menu slot="dropdown" :visible-arrow="false">
        <el-dropdown-item command="reload" :disabled="!tabCommandEnables.reload" icon="el-icon-refresh">重新加载</el-dropdown-item>
        <el-dropdown-item command="close-this" divided :disabled="!tabCommandEnables.closeThis" icon="el-icon-close">关闭</el-dropdown-item>
        <el-dropdown-item command="close-left"  :disabled="!tabCommandEnables.closeLeft" icon="el-icon-close">关闭左侧标签页</el-dropdown-item>
        <el-dropdown-item command="close-right" :disabled="!tabCommandEnables.closeRight" icon="el-icon-close">关闭右侧标签页</el-dropdown-item>
        <el-dropdown-item command="close-other" :disabled="!tabCommandEnables.closeOther" icon="el-icon-close">关闭其它标签页</el-dropdown-item>
        <el-dropdown-item command="close-all"   :disabled="!tabCommandEnables.closeAll" icon="el-icon-close">关闭所有标签页</el-dropdown-item>
        <el-dropdown-item command="move-to-start" divided :disabled="!tabCommandEnables.moveToStart" icon="el-icon-back">移动到开头</el-dropdown-item>
        <el-dropdown-item command="move-to-end" :disabled="!tabCommandEnables.moveToEnd" icon="el-icon-right">移动到末尾</el-dropdown-item>
        <el-dropdown-item command="full-screen" :disabled="!tabCommandEnables.fullScreen" divided icon="el-icon-full-screen">全屏此标签页</el-dropdown-item>

      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script>
import fullScreen from '@/utils/fullscreen';

export default {
  props: ['paneHeight'],
  data() {
    return {
      tabs: [],
      activeTabKey: null,
      cmdTab: null
    };
  },
  computed: {
    tabCommandEnables() {
      const { tabs, cmdTab } = this;
      const cmdTabIndex = cmdTab ? tabs.findIndex(tab => tab.key == cmdTab.key) : -1;
      return {
        reload: true,
        closeThis: true,
        closeOther: tabs.length > 1,
        closeLeft: cmdTabIndex > 0,
        closeRight: cmdTabIndex < tabs.length - 1,
        closeAll: true,
        moveToStart: cmdTabIndex > 0,
        moveToEnd: cmdTabIndex < tabs.length - 1,
        fullScreen: cmdTab && cmdTab.key == this.activeTabKey
      };
    }
  },
  watch: {
    activeTabKey(key, lastActiveTabKey) {
      if (key) {
        this.$emit('activeTabChange', key);
      }
    }
  },
  mounted() {
    let menu = this.$refs.tabsDropdown;
    document.addEventListener('click', () => {
      menu.visible = false;
    });
  },
  methods: {
    onTabClick(clickTab) {
      this.activeTabKey = clickTab.name;
      this.$emit('tab-click', clickTab);
    },
    onTabRemove(key) {
      this.$emit('remove', key);

      let { tabs, activeTabKey } = this;
      // 如果要关闭的是当前正活动的
      if (key == activeTabKey) {
        // 找到下一个将变成活动的
        if (tabs.length - 1) {
          let index = tabs.findIndex(tab => tab.key == key);
          activeTabKey = (index > 0 ? tabs[index - 1] : tabs[index + 1]).key;
          this.activeTabKey = activeTabKey;
        } else {
          activeTabKey = null;
        }
      }

      // 删除要关闭的
      this.tabs = tabs.filter(tab => tab.key != key);
    },
    addTab(newTab) {
      let tabs = this.tabs;
      let index = -1;
      if (newTab.parentTabKey) {
        // 将新tab插入到parentTab的后面（右边）
        const parentTabIndex = tabs.findIndex(tab => tab.key == newTab.parentTabKey);
        index = parentTabIndex + 1;
        tabs.splice(index, 0, newTab);
      } else {
        // 插入到最后
        index = tabs.length;
        tabs.push(newTab);
      }

      this.$nextTick(() => {
        setTimeout(() => {
          this.$el.querySelector('.el-tabs__header').oncontextmenu = (event) => {
            return false;
          };

          let tabItemEl = this.$el.querySelector('.el-tabs__nav').children[index];

          tabItemEl.oncontextmenu = (event) => {
            this.cmdTab = newTab;
            let menu = this.$refs.tabsDropdown;
            menu.visible = false;
            menu.$nextTick(() => {
              menu.$el.style.left = (event.clientX + 70) + 'px';
              menu.$el.style.top = (event.clientY - 12) + 'px';
              menu.visible = true;
            });
            return false;
          }
        }, 0)
      });
    },
    onContextmenuCommand(cmd) {
      this.execCommand(cmd);
    },
    removeTab(key) {
      this.onTabRemove(key);
    },
    removeActiveTab() {
      this.removeTab(this.activeTabKey);
    },
    findTabByKey(key) {
      return this.tabs.find(tab => tab.key == key);
    },
    execCommandForActiveCmd(cmd) {
      this.cmdTab = this.findTabByKey(this.activeTabKey);
      this.execCommand(cmd);
    },
    execCommand(cmd) {
      switch (cmd) {
        case 'reload':
          let { cmdTab } = this;
          let tmp = cmdTab.content;
          cmdTab.content = null;
          cmdTab.loading = true;
          this.$nextTick(() => {
            cmdTab.content = tmp;
            if (cmdTab.options.type != 'iframe') {
              setTimeout(() => {
                cmdTab.loading = false;
              }, 200);
            }
          });
          break;
        case 'close-this':
          this.removeTab(this.cmdTab.key);
          break;
        case 'close-other':
          this.tabs = this.tabs.filter(tab => tab.key == this.cmdTab.key);
          this.activeTabKey = this.cmdTab.key;
          break;
        case 'close-left':
          this.tabs = this.tabs.slice(this.tabs.findIndex(tab => tab.key == this.cmdTab.key));
          if (!this.findTabByKey(this.activeTabKey)) {
            this.activeTabKey = this.cmdTab.key;
          }
          break;
        case 'close-right':
          this.tabs = this.tabs.slice(0, this.tabs.findIndex(tab => tab.key == this.cmdTab.key) + 1);
          if (!this.findTabByKey(this.activeTabKey)) {
            this.activeTabKey = this.cmdTab.key;
          }
          break;
        case 'close-all':
          this.tabs = [];
          this.activeTabKey = null;
          break;
        case 'move-to-start':
          this.tabs = [this.cmdTab].concat(this.tabs.filter(tab => tab.key != this.cmdTab.key));
          break;
        case 'move-to-end':
          this.tabs = this.tabs.filter(tab => tab.key != this.cmdTab.key).concat(this.cmdTab);
          break;
        case 'full-screen':
          this.getTabPaneComponents().forEach((tabPane) => {
            if (tabPane.name == this.cmdTab.key) {
              fullScreen.switch(tabPane.$el);
            }
          });
          break;
      }
    },
    getTabPaneComponents() {
      return this.$children[0].$children.slice(1);
    }
  }
}
</script>

<style lang="scss">
@import "~element-ui/packages/theme-chalk/src/common/var.scss";
.home-main > div > .el-tabs--border-card {
  border: none;
  box-shadow: none;
  background: transparent;
  > .el-tabs__header {
    background: transparent;
    border-bottom: none;
    > .el-tabs__nav-wrap {
      margin-bottom: 0px;

      > .el-tabs__nav-prev {
        left: 4px;
      }
      > .el-tabs__nav-next {
        right: 4px;
      }
    }
  }
  > .el-tabs__header .el-tabs__nav {
    padding: 4px 0px;
    > .el-tabs__item {
      height: 32px;
      line-height: 32px;
      margin-left: 4px;
      border: none;
      background-color: #fff;
      border-radius: 3px;
      font-weight: normal;
      transition: none;
      user-select: none;
      &:hover {
        background: #fafcff;
      }
    }
    > .el-tabs__item:not(.is-active):not(:hover) {
      color: $--color-text-regular;
    }
    > .el-tabs__item.is-active {
      background: #ecf5ff;
      color: $--color-primary;
    }

    > .el-tabs__item > .el-icon-close {
      font-weight: bold;
      transition-duration: 0s !important;
    }
  }

  > .el-tabs__content {
    padding: 0px 4px;
    overflow: auto;

    > .el-tab-pane {
      background-color: #f0f2f5;
    }
  }
}
</style>